<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue'
import { useClassnames } from '../../utils/gen-class/index'
import { omit, pick } from 'lodash-es'
import { type InputProps, originInputProps } from './interface'

// omit 排除我们不需要的元素, pick选取我们需要的元素

defineOptions({
  name: 'TInput',
  inheritAttrs: false,   // 组织默认继承，最外层的这个div将不会继承属性
})
const props = defineProps<InputProps>()
const emit = defineEmits<{
  'update:modelValue': [string]
}>()
defineSlots<{
  prefix(): any
  suffix(): any
}>()
const { cx, c, cm, ce } = useClassnames('input')
const inputRef = ref<HTMLInputElement>()

const cls = cx(() => {
  return {
    [c()]: true,
    [c(cm('disabled'))]: props.disabled,
    [c(cm(props.size!))]: !!props.size,
  }
})

const inputCls = cx(() => {
  return {
    [c('input')]: true,
  }
})


// 受控状态 v-model不绑定，输入不了东西
function setInputValue() {
  const _input = inputRef.value
  if (!_input || _input.value === props.modelValue)
    return

  _input.value = props.modelValue ?? ''
}

function handleInput(e: Event) {
  const target = e.target as HTMLInputElement
  if (props.modelValue === target.value)
    return
  emit('update:modelValue', target.value)
  nextTick(() => {
    setInputValue()
  })
}
onMounted(() => {
  setInputValue()
})

function focus() {
  inputRef.value?.focus()
}

function blur() {
  inputRef.value?.blur()
}
defineExpose({
  focus,
  blur,
})
</script>

<template>
 
  <div :class="cls" v-bind="omit($attrs, originInputProps)">
    <span v-if="$slots.prefix" :class="c(ce('prefix'))">
      <slot name="prefix" />
    </span>
    <input ref="inputRef" v-bind="pick($attrs, originInputProps)" :disabled="disabled" :class="inputCls"
      :value="modelValue" @input="handleInput">
    <span v-if="$slots.suffix" :class="c(ce('suffix'))">
      <slot name="suffix" />
    </span>
  </div>
</template>
<style scoped lang="less">
@import "./style/index.less";
</style>
